import React, { act, useCallback, useEffect, useRef, useState } from "react";
import { Card, Row, Col, Table, Tabs } from "antd";
import {
  ArrowUpOutlined,
  ShoppingOutlined,
  UserOutlined,
  DollarOutlined,
  LineChartOutlined,
} from "@ant-design/icons";
import * as echarts from "echarts";
import useCloseLoadingOnMount from "../../utils/hook/useCloseLoadingOnMount";
import statisticsApi from "../../apis/statisticsApi";
import StatisticsCard from "../../components/StatisticsCard";

const tabItems = [
  { label: "今日", key: "date" },
  { label: "本周", key: "week" },
  { label: "本月", key: "month" },
  { label: "本年", key: "year" },
];

let salesChart, productChart, orderChart, unitPriceChart;

const Home = () => {
  useCloseLoadingOnMount();
  const [statistics, setStatistics] = useState();
  const [activeTab, setActiveTab] = useState("date");
  const salesChartRef = useRef(null);
  const productChartRef = useRef(null);
  const orderChartRef = useRef(null);
  const unitPriceChartRef = useRef(null);

  useEffect(() => {
    const fetchData = async () => {
      const res = await statisticsApi.getHomeStatistics(activeTab);
      if (res.status >= 0) {
        salesChart.setOption({
          series: [
            {
              data: [res.data.chart1Data],
            },
          ],
        });
        productChart.setOption({
          series: [
            {
              data: [res.data.chart2Data],
            },
          ],
        });
        orderChart.setOption({
          series: [
            {
              data: [res.data.chart3Data],
            },
          ],
        });
        unitPriceChart.setOption({
          series: [
            {
              data: [res.data.chart4Data],
            },
          ],
        });
      }
      setStatistics(res.data);
    };
    fetchData();
  }, [activeTab]);

  useEffect(() => {
    const fetchData = async () => {
      const res = await statisticsApi.getHomeStatistics(activeTab);
      if (res.status >= 0) {
        // 初始化销售趋势图表
        salesChart = echarts.init(salesChartRef.current);
        salesChart.setOption({
          title: { text: "销售趋势", left: "center" },
          tooltip: {},
          xAxis: {
            type: "category",
            data: res.data.chart1Data.map((item) => item.time),
          },
          yAxis: { type: "value" },
          series: [
            {
              data: res.data.chart1Data.map((item) => item.sales),
              type: "line",
              smooth: true,
              areaStyle: {},
              color: "#1890ff",
            },
          ],
        });

        // 初始化商品销售柱状图
        productChart = echarts.init(productChartRef.current);
        productChart.setOption({
          title: { text: "品类销售排行", left: "center" },
          tooltip: {},
          xAxis: {
            type: "category",
            data: res.data.chart2Data.map((item) => item.category),
          },
          yAxis: { type: "value" },
          series: [
            {
              type: "bar",
              data: res.data.chart2Data.map((item) => item.sales),
              itemStyle: {
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                  { offset: 0, color: "#83bff6" },
                  { offset: 1, color: "#1882ff" },
                ]),
              },
            },
          ],
        });

        // 初始化订单状态饼图
        orderChart = echarts.init(orderChartRef.current);
        orderChart.setOption({
          title: { text: "订单状态分布", left: "center" },
          tooltip: { trigger: "item" },
          series: [
            {
              type: "pie",
              radius: "60%",
              data: res.data.chart3Data,
              emphasis: {
                itemStyle: {
                  shadowBlur: 10,
                  shadowOffsetX: 0,
                  shadowColor: "rgba(0, 0, 0, 0.5)",
                },
              },
            },
          ],
        });

        // 初始化订单总价分布饼图
        unitPriceChart = echarts.init(unitPriceChartRef.current);
        unitPriceChart.setOption({
          title: { text: "订单总价分布", left: "center" },
          tooltip: { trigger: "item" },
          series: [
            {
              type: "pie",
              radius: "60%",
              data: res.data.chart4Data,
              emphasis: {
                itemStyle: {
                  shadowBlur: 10,
                  shadowOffsetX: 0,
                  shadowColor: "rgba(0, 0, 0, 0.5)",
                },
              },
            },
          ],
        });
      }
      setStatistics(res.data);
    };
    fetchData();
    // 响应式调整
    const resizeHandler = () => {
      salesChart.resize();
      productChart.resize();
      orderChart.resize();
      unitPriceChart.resize();
    };
    window.addEventListener("resize", resizeHandler);

    // 每十五秒刷新一次数据;
    let interval = setInterval(() => {
      fetchData();
    }, 15000);

    return () => {
      window.removeEventListener("resize", resizeHandler);
      salesChart.dispose();
      productChart.dispose();
      orderChart.dispose();
      clearInterval(interval);
    };
  }, [activeTab]);

  const handleTabClick = (activeKey) => {
    setActiveTab(activeKey);
  };

  return (
    <div>
      <Tabs
        activeKey={activeTab}
        type="card"
        items={tabItems}
        onTabClick={handleTabClick}
      ></Tabs>
      <Row gutter={[24, 24]}>
        {/* 统计卡片 */}
        <Col xs={24} sm={12} xl={6}>
          <StatisticsCard
            icon={<DollarOutlined />}
            name="销售额"
            data={statistics?.sumSales ?? "-"}
            suffix="¥"
            mom={
              statistics?.sumSalesMom != null
                ? (statistics?.sumSalesMom * 100).toFixed(2)
                : null
            }
            activeTab={activeTab}
          />
        </Col>
        <Col xs={24} sm={12} xl={6}>
          <StatisticsCard
            icon={<ShoppingOutlined />}
            name="订单数"
            data={statistics?.sumOrderCount ?? "-"}
            suffix=""
            mom={
              statistics?.sumOrderCountMom != null
                ? (statistics?.sumOrderCountMom * 100).toFixed(2)
                : null
            }
            activeTab={activeTab}
          />
        </Col>
        <Col xs={24} sm={12} xl={6}>
          <StatisticsCard
            icon={<UserOutlined />}
            name="新用户"
            data={statistics?.newUserCount ?? "-"}
            suffix="个"
            mom={
              statistics?.newUserCountMon != null
                ? (statistics?.newUserCountMon * 100).toFixed(2)
                : null
            }
            activeTab={activeTab}
          />
        </Col>
        <Col xs={24} sm={12} xl={6}>
          <StatisticsCard
            icon={<LineChartOutlined />}
            name="转化率"
            data={
              statistics?.conversionRate != null
                ? statistics?.conversionRate * 100
                : "-"
            }
            suffix="%"
            mom={
              statistics?.conversionRateMom != null
                ? (statistics?.conversionRateMom * 100).toFixed(2)
                : null
            }
            activeTab={activeTab}
          />
        </Col>
      </Row>

      <Row gutter={[24, 24]} style={{ marginTop: 24 }}>
        <Col xs={24} lg={12}>
          <div
            ref={salesChartRef}
            style={{ height: 400, background: "#fff", padding: 24 }}
          />
        </Col>
        <Col xs={24} lg={12}>
          <div
            ref={productChartRef}
            style={{ height: 400, background: "#fff", padding: 24 }}
          />
        </Col>
      </Row>

      <Row gutter={[24, 24]} style={{ marginTop: 24 }}>
        <Col xs={24} lg={12}>
          <div
            ref={orderChartRef}
            style={{ height: 400, background: "#fff", padding: 24 }}
          />
        </Col>
        <Col xs={24} lg={12}>
          <div
            ref={unitPriceChartRef}
            style={{ height: 400, background: "#fff", padding: 24 }}
          />
        </Col>
      </Row>
    </div>
  );
};

export default Home;
